﻿using Shared.Method;
using Shared.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StatisticsServer
{
    public partial class Statistics : Form
    {
        public Statistics()
        {
            InitializeComponent();
        }

        private void Statistics_Load(object sender, EventArgs e)
        {
            //string startTime = DateTime.Now.AddHours(-1).ToString("yyyy/MM/dd HH:00:00");
            //string endTime = DateTime.Now.ToString("yyyy/MM/dd HH:00:00");
            Client.MethodWcf.KEY = "RssPmq&AwYcc7<98Bux";
            TaskRun();
        }

        private void TaskRun()
        {
            Task.Run(()=>
            {
                //do one work, statistical product data
                //one hour run a time
                //every 5 min
                //goto begin;
#if true
                int currentMinute = DateTime.Now.Minute;

                if (currentMinute > 4)
                {
                    //wait next hour and four minute
                    System.Threading.Thread.Sleep((64 - currentMinute) * 60 * 1000);
                }
                else if (currentMinute < 4)
                {
                    System.Threading.Thread.Sleep((4 - currentMinute) * 60 * 1000);
                }
#endif

                //begin:

                string startTime;
                string endTime;

                PROCESS processW = new PROCESS();
                PRODUCT_COUNT_DATA dataU = new PRODUCT_COUNT_DATA();

                while (true)
                {
                    Shared.SoftMethod.SoftShared.SetControl(this, this.richTextBoxMsg, string.Empty);

                    startTime = DateTime.Now.AddHours(-1).ToString("yyyy/MM/dd HH:00:00");
                    endTime = DateTime.Now.ToString("yyyy/MM/dd HH:00:00");

                    //get last hour's all process items
                    //processW.Clear();
                    //processW.SetWhere(
                    //    $"END_TIME>'{startTime}' AND END_TIME<='{endTime}'"
                    //    );

                    //var selectProcess = Client.MethodWcf.SelectProcessClient(processW);

                    //use view process
                    var listProcess = Client.MethodWcf.SelectJsonClient<List<PROCESS>>($"SELECT * FROM View_Process WHERE END_TIME>'{startTime}' AND END_TIME<='{endTime}'");

                    if (listProcess!=null&&listProcess.Count>0)
                    {
                        //statistical data
                        //get lines and nodes
                        var list = (from p in listProcess
                                    where p.LINE_ID!=null && p.NODE_ID!=null
                                    select new { p.LINE_ID, p.NODE_ID }).Distinct().ToList();

                        StringBuilder insertProductCountBuf = new StringBuilder();
                        insertProductCountBuf.AppendLine(
                            "BEGIN	TRY BEGIN TRANSACTION");

                        for (int i = 0; list != null && list.Count > 0 && i < list.Count; i++)
                        {
                            //Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, $"line id:{list[i].LINE_ID}, node id:{list[i].NODE_ID}");

                            if (list[i].LINE_ID == null || list[i].NODE_ID == null) continue;

                            dataU.Clear();
                            dataU.SetUpdate();
                            dataU.COUNT_DATE = DateTime.Today;
                            dataU.COUNT_TIME = DateTime.Now.Hour - 1;
                            dataU.LINE_ID = list[i].LINE_ID.Value;
                            dataU.NODE_ID = list[i].NODE_ID.Value;
                            dataU.TOTAL = (from p in listProcess
                                           where p.LINE_ID == list[i].LINE_ID && p.NODE_ID == list[i].NODE_ID
                                           select p.MAC).Distinct().Count();

                            dataU.PASS = (from p in listProcess
                                          where p.LINE_ID == list[i].LINE_ID && p.NODE_ID == list[i].NODE_ID && p.TEST_RESULT == "Y"
                                          select p.MAC).Distinct().Count();

                            //in passing mac,not in not pass mac
                            //pass - ng = one pass
                            dataU.ONETIME_PASS =
                            (from p in listProcess
                             where p.LINE_ID == list[i].LINE_ID && p.NODE_ID == list[i].NODE_ID && p.TEST_RESULT == "Y"
                             select p.MAC).Distinct().Count()
                                                  -
                                                   (from p in listProcess
                                                    where p.LINE_ID == list[i].LINE_ID && p.NODE_ID == list[i].NODE_ID && p.TEST_RESULT == "N"
                                                    select p.MAC).Distinct().Count();

                            if (dataU.ONETIME_PASS < 0) dataU.ONETIME_PASS = 0;

                            insertProductCountBuf.AppendLine(ObjectToSQL.ObjectToInsertSql(dataU));
                        
                        }

                        insertProductCountBuf.AppendLine("COMMIT TRANSACTION    END TRY    BEGIN CATCH  ROLLBACK TRANSACTION    END CATCH");

                        Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, insertProductCountBuf.ToString());

                        int rows = Client.MethodWcf.ExecuteSQLClient(insertProductCountBuf.ToString());

                        Shared.SoftMethod.SoftShared.AppendText(this, this.richTextBoxMsg, $"写入行数：{rows}");
                    }

                    //one hour, five minute
                    System.Threading.Thread.Sleep(60 * 60 * 1000);
                }
            });
        }

        private void Statistics_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            //e.CloseReason();
        }
    }
}
